package com.itserver.utils;


import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class Ip2Region {
    private static byte[] dbBin = null;
    private static Searcher searcher = null;

    private final Config config;

    public Ip2Region(Config config) {
        this.config = config;
    }

    @PostConstruct
    private void init() {
        try {
            log.info("初始化ip2region");
            synchronized (Ip2Region.class) {
                if (dbBin == null) {
                    dbBin = Searcher.loadContentFromFile(config.getIp2regionUrl());
                    searcher = Searcher.newWithBuffer(dbBin);
                }
            }
        } catch (IOException e) {
            log.error("ip2region 初始化失败", e);
            throw new RuntimeException("ip2region 初始化失败", e);
        }
    }

    public static String getCity(String ip) throws Exception {
        if (ip == null || ip.isEmpty()) {
            return null;
        }
        if (searcher == null) {
            throw new IllegalStateException("Ip2Region 尚未初始化");
        }
        return searcher.search(ip);
    }
}
